package com.goldenautumn.prefabricate.activity.search

import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.activity.category.CategoryLayoutAdapter
import com.goldenautumn.prefabricate.activity.mall.GoodsDetailsActivity
import com.goldenautumn.prefabricate.business.entity.GoodsInfoVO
import com.goldenautumn.prefabricate.business.entity.SearchParams
import com.goldenautumn.prefabricate.business.mall.GoodsInfoUiState
import com.goldenautumn.prefabricate.business.mall.MallViewModel
import com.goldenautumn.prefabricate.databinding.ActivitySearchBinding
import com.goldenautumn.prefabricate.utils.Constants
import com.goldenautumn.prefabricate.utils.Constants.BUSINESS_PAGE_DATA
import com.goldenautumn.prefabricate.utils.Constants.SEARCH_HISTORY_DELETE
import com.goldenautumn.prefabricate.utils.Constants.SEARCH_HISTORY_INSERT
import com.goldenautumn.prefabricate.utils.Constants.SEARCH_HISTORY_QUERY
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.withContext
import qncx.external.common.Global
import qncx.external.common.base.BaseActivity
import qncx.external.common.compat.gone
import qncx.external.common.compat.visible
import qncx.external.common.room.RoomSql
import qncx.external.common.room.table.HistorySearch
import qncx.external.common.utils.intent
import qncx.external.common.widget.shapeview.shape.ShapeButton

class SearchActivity : BaseActivity<ActivitySearchBinding>() {

    private val mHotAdapter by lazy {
        HotSearchAdapter()
    }

    private val mResultAdapter by lazy {
        CategoryLayoutAdapter()
    }

    private var arrangeType = 1 //1线性 2网格

    private val mMallModel by viewModels<MallViewModel>()

    override fun getLayoutId(): Int = R.layout.activity_search

    override suspend fun main() {
        ImmersionBar.setTitleBar(this, mBinding.toolbar)
        mBinding.backBtn.setOnClickListener { onBackPressedDispatcher.onBackPressed() }
        mBinding.resultRv.layoutManager = LinearLayoutManager(this)
        mBinding.popularRv.layoutManager = LinearLayoutManager(this)
        mBinding.keywordRv.layoutManager = LinearLayoutManager(this)
        mBinding.popularRv.adapter = mHotAdapter
        mBinding.resultRv.adapter = mResultAdapter
        mBinding.keywordRv.adapter = mHotAdapter
        mResultAdapter.setStateViewLayout(this, R.layout.recycler_empty_view)
        var msg = mResultAdapter.stateView?.findViewById<TextView>(R.id.prompt_content)
        msg?.text = getString(R.string.search_not_goods)
        msg?.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(this, R.mipmap.ic_empty_order), null, null)

        updateHistoryDao(SEARCH_HISTORY_QUERY)
//        mHotAdapter.submitList(arrayListOf("","","","",""))
        mBinding.deleteBtn.setOnClickListener { Global.launch {updateHistoryDao(SEARCH_HISTORY_DELETE)} }
        KeyboardUtils.showSoftInput(mBinding.keyword)
        mBinding.keyword.setOnEditorActionListener { _, actionId, _ ->
            if(actionId == EditorInfo.IME_ACTION_SEARCH ){
                var content = mBinding.keyword.text?.trim().toString()
                if(content.isEmpty()) return@setOnEditorActionListener true
                Global.launch { updateHistoryDao(SEARCH_HISTORY_INSERT,HistorySearch(content = content)) }
                KeyboardUtils.hideSoftInput(mBinding.keyword)
                setGoodsData(1)
                mMallModel.getGoodsList(SearchParams(search = content))
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }

        mBinding.menuBtn.setOnClickListener {
            if(mResultAdapter.items.isEmpty()) return@setOnClickListener
            var item = mResultAdapter.getItem(0)
            setGoodsData(if(item?.itemType == 1) 2 else 1)
        }

        mBinding.bestMatch.setOnClickListener {
            onTabSelect(1)
            var content = mBinding.keyword.text?.trim().toString()
            mMallModel.getGoodsList(SearchParams(search = content))
        }
        mBinding.sales.setOnClickListener {
            onTabSelect(2)
            var content = mBinding.keyword.text?.trim().toString()
            //排序方式 all(默认排序) sales（销量）price（价格）
            mMallModel.getGoodsList(SearchParams(search = content, sortType = "sales"))
        }
        mBinding.price.setOnClickListener {
            mBinding.price.tag = if(mBinding.price.tag == null || mBinding.price.tag == "NO") "YES" else "NO"
            onTabSelect(3)
            var content = mBinding.keyword.text?.trim().toString()
            mMallModel.getGoodsList(SearchParams(search = content, sortType = "price", sortPrice = if(mBinding.price.tag == "YES") "0" else "1"))
        }

        mResultAdapter.setOnItemClickListener{ adapter,_,position ->
            var item = adapter.getItem(position)
            startActivity(GoodsDetailsActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,item?.goods_id))
        }

        KeyboardUtils.registerSoftInputChangedListener(this) {
            if(it > 0) {
                mBinding.resultBody.gone()
                var content = mBinding.keyword.text?.trim().toString()
                if(content.isNullOrEmpty()) {
                    mBinding.keywordRv.gone()
                    mBinding.historyRv.removeAllViews()
                    Global.launch { updateHistoryDao(SEARCH_HISTORY_QUERY) }
                } else {
                    mBinding.keywordRv.visible()
                }
            }
        }

        mBinding.keyword.doAfterTextChanged {
            if(it?.trim()?.toString()?.length == 0){
                mBinding.keywordRv.visible()
                mBinding.historyRv.removeAllViews()
                Global.launch { updateHistoryDao(SEARCH_HISTORY_QUERY) }
            } else {
                mBinding.keywordRv.gone()
            }
        }

        while (isActive) {
            select {
                mMallModel.goodsDetailsRequests.onReceive {
                    when(it) {
                        is GoodsInfoUiState.GoodsList -> {
                            mResultAdapter.isStateViewEnable = true
                            it.goodsList.forEach { it.itemType = arrangeType }
                            mResultAdapter.submitList(it.goodsList)
                        }
                        else -> {}
                    }
                }
            }
        }

    }

   suspend fun updateHistoryDao(type:Int,item: HistorySearch? = null){
        withContext(Dispatchers.IO) {
            var dao = RoomSql.get()?.searchDao
            if(type == SEARCH_HISTORY_INSERT){
                var oldItem = dao?.getByIdHistory("${item?.content}")
                if(oldItem?.size == 0) item?.let { dao?.insertHistorySearch(it) }
            } else if(SEARCH_HISTORY_QUERY == type) {
                var dataList = dao?.getHistoryList()
                updateAdapter(dataList)
            } else if(SEARCH_HISTORY_DELETE == type) {
                dao?.deleteAll()
                updateAdapter(arrayListOf())
            }
        }
    }

    suspend fun updateAdapter(data:List<HistorySearch>?){
        withContext(Dispatchers.Main) {
            if(data?.size == 0) {
                mBinding.historyRv.removeAllViews()
                mBinding.historyBody.gone()
            } else mBinding.historyBody.visible()
            data?.forEach { item ->
                var searchKey = layoutInflater.inflate(R.layout.item_search_key, mBinding.historyRv, false)
                mBinding.historyRv.addView(searchKey.apply {
                    this.findViewById<ShapeButton>(R.id.searchKey).text = item.content
                    setOnClickListener {
                        mBinding.keyword.setText("${item.content}")
                        mBinding.keyword.setSelection(item.content?.length ?: 0)
                        setGoodsData(1)
                        mMallModel.getGoodsList(SearchParams(search = item.content))
                    }
                })
            }
        }
    }

    fun setGoodsData(type: Int) {
        arrangeType = type
        if(arrangeType == 1)  mBinding.resultRv.layoutManager = LinearLayoutManager(this)
        else  mBinding.resultRv.layoutManager = StaggeredGridLayoutManager(2, RecyclerView.VERTICAL)
        mBinding.menuBtn.setImageResource(if(arrangeType == 1) R.mipmap.ic_product_line_grid_1 else R.mipmap.ic_product_line_grid)
        mResultAdapter?.items?.forEach { it.itemType = arrangeType }
        mResultAdapter.notifyDataSetChanged()
        mBinding.resultBody.visible()
    }

    fun onTabSelect(type:Int,isPrice:Boolean? = true){
        when(type) {
            1 -> {
                mBinding.bestMatch.setTextColor(ContextCompat.getColor(this,R.color.colorPrimary))
                mBinding.sales.setTextColor(ContextCompat.getColor(this, qncx.external.common.R.color.color_999999))
                mBinding.price.setTextColor(ContextCompat.getColor(this, qncx.external.common.R.color.color_999999))
                mBinding.price.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.mipmap.ic_price_default),null, null, null)
                mBinding.price.tag = null
            }
            2 -> {
                mBinding.bestMatch.setTextColor(ContextCompat.getColor(this, qncx.external.common.R.color.color_999999))
                mBinding.sales.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary))
                mBinding.price.setTextColor(ContextCompat.getColor(this, qncx.external.common.R.color.color_999999))
                mBinding.price.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.mipmap.ic_price_default),null, null, null)
                mBinding.price.tag = null
            }
            3 -> {
                mBinding.bestMatch.setTextColor(ContextCompat.getColor(this, qncx.external.common.R.color.color_999999))
                mBinding.sales.setTextColor(ContextCompat.getColor(this, qncx.external.common.R.color.color_999999))
                mBinding.price.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary))
                mBinding.price.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, if(mBinding.price.tag == "YES") R.mipmap.ic_price_dwon else R.mipmap.ic_price_top),null, null, null)
            }
        }
    }

    override fun onDestroy() {
        KeyboardUtils.hideSoftInput(mBinding.keyword)
        super.onDestroy()
    }


}